using System;
using System.Collections.Generic;
using Kotonoha.Server.Dictionaries;
using Kotonoha.Server.Examples;
using NHibernate;
using NHibernate.Criterion;
using System.Linq;

namespace Kotonoha.Server.Db.Dao {
    public class DictDao : DaoBase {
        public DictDao(ISession session) : base(session) {}

        public CharEntry findChar(string ch) {
            ICriteria criteria = session.CreateCriteria(typeof(CharEntry));
            criteria.Add(Restrictions.Eq("Writing", ch));
            return criteria.UniqueResult<CharEntry>();
        }

        public IList<WordEntry> findWordByWriting(string writing) {
            IQuery query = session.CreateQuery("from WordEntry w join w.Writings wr where wr = :val");
            query.SetString("val", writing);
            return query.List<WordEntry>();
        }

        public IList<ExampleEntry> findExamples(string word, int max) {
            IQuery q =
                session.CreateQuery(
                    "select i from ExampleInfo i join i.Word w join w.Writings wr where wr = :val");
            q.SetString("val", word);
            IList<ExampleInfo> entries = q.List<ExampleInfo>();
            var enumerable = entries
                .Where(e => e.Example.Content.Length < 50)
                .OrderBy(en => en.Recommended)
                .GroupBy(en => en.Number)
                .Select(g => g.Take(max))
                .SelectMany(g => g)
                .Select(i => i.Example);
            return enumerable.ToList();
        }
    }
}